<template>
    <van-popup v-model="show" position="bottom" @close="close" :closeOnClickOverlay="closeOnClickOverlay" :style="{'--themescolor': themes.color}">
        <div class="toolbar">
            <div class="cancel" @click="onCancel" :style="{'color': cancelColor}">{{cancelText}}</div>
            <div class="title">{{title}}</div>
            <div class="confirm" @click="onConfirm" :style="{'color': confirmColor}">{{confirmText}}</div>
        </div>
        <div class="tabs-wrap"> 
            <div class="tabs__nav">
                <div 
                    v-for="(item,index) in location" :key="index"
                    class="tab" 
                    :class="[selectIndex == index ? 'on' : '', item.selectName   ? 'action' : '']"
                    @click="switchTab(item,index)" 
                    
                >
                    {{item.selectName ?  item.selectName :  item.name}}
                </div>
            </div>
        </div>

        <div class="tabs-content">
            <div class="tab-pane" :style="{'display': selectIndex == 0 ? 'block' : 'none'}">
                <div class="cascade-selectorlist" v-if="provinceData">
                    <div 
                        v-for="(item, index) in provinceData" :key="index"
                        class="item"
                        :class="item.key ==  location[selectIndex].key ? 'action' : ''"
                        @click="switchAddress(item[valueName],item[keyName],'cityData')" 
                        
                    > 
                        {{item[valueName]}}
                    </div>
                </div>
            </div>

            <div class="tab-pane" :style="{'display': selectIndex == 1 ? 'block' : 'none'}">
                <div class="cascade-selectorlist" v-if="cityData">
                    <div 
                        v-for="(item, index) in cityData" :key="index"
                        class="item"
                        :class="item.key ==  location[selectIndex].key ? 'action' : ''"
                        @click="switchAddress(item[valueName],item[keyName],'areaData')" 
                        
                    > {{item[valueName]}}</div>
                </div>
            </div>


            <div class="tab-pane" :style="{'display': selectIndex == 2 ? 'block' : 'none'}">
                <div class="cascade-selectorlist" v-if="areaData">
                    <div 
                        v-for="(item, index) in areaData" :key="index"
                        class="item"
                        :class="item.key ==  location[selectIndex].key ? 'action' : ''"
                        @click="switchAddress(item[valueName],item[keyName],'townsData')" 
                        
                    > {{item[valueName]}}</div>
                </div>
            </div>

            <div class="tab-pane" :style="{'display': selectIndex == 3 ? 'block' : 'none'}">
                <div class="cascade-selectorlist" v-if="townsData">
                    <div 
                        v-for="(item, index) in townsData" :key="index"
                        class="item"
                        :class="item.key ==  location[selectIndex].key ? 'action' : ''"
                        @click="switchAddress(item[valueName],item[keyName],'')" 
                        
                    > {{item[valueName]}}</div>
                </div>
            </div>
        </div>

    </van-popup>
</template>

<script>
import { loadProvincesByMode,loadCitiesByMode,loadAreasByMode ,loadTownsByMode} from "api/common/common.js";
import {mapState} from 'vuex';
export default {
    props: {
        mode: {
            type: String,
			default: 'id'
        },
        defaultValue: {
            type: Array,
            default: () => {
                return []
            }
        },
        // 通过双向绑定控制组件的弹出与收起
		value: {
			type: Boolean,
			default: false
        },
        closeOnClickOverlay: {
            type: Boolean,
			default: true
        },
        // "取消"按钮的颜色
		cancelColor: {
			type: String,
			default: '#606266'
        },
        // "确定"按钮的颜色
		confirmColor: {
			type: String,
			default: '#2979ff'
        },
        // 是否允许通过点击遮罩关闭Picker
		maskCloseAble: {
			type: Boolean,
			default: true
        },
        // 自定义value属性名
		valueName: {
			type: String,
			default: 'value'
		},
		// 自定义key属性名
		keyName: {
			type: String,
			default: 'key'
        },
        // 顶部标题
		title: {
			type: String,
			default: ''
		},
		// 取消按钮的文字
		cancelText: {
			type: String,
			default: '取消'
		},
		// 确认按钮的文字
		confirmText: {
			type: String,
			default: '确认'
		}
    },
    watch: {
        value(val) {
            this.show = val
            if (val) {
                !this.isinit && this.init()
                this.isinit = true
            }
        },
        defaultValue(val) {
            this.defaultlocation = val
        }
    },
    computed: {
        ...mapState(['themes']),
        a() {
            return this.defaultValue
        }
    },
    data () {
        return {
            show: this.value,
            selectIndex:0,
            location: [
                { name: '请选择', selectName: '' ,key: ''},  
                // { name: '城市', selectName: '', key: ''}, 
                // { name: '区县', selectName: '', key: ''},
                // { name: '街道/乡镇', selectName: '', key: ''}
            ],
            setSelectValue: [],

            provinceData: '',  //省 
            cityData: '',  //市
            areaData: '', //区
            townsData: '',  //街道
            defaultlocation: [],

            isinit: false
        }
    },
    mounted () {
        

        
    },
   
    methods: {

        init() {
            if ((this.defaultValue.length > 0 && this.defaultValue[0].key)) {
                let newDefaultValue = this.defaultValue.filter(item => item.key)
                let newLocation = []

                newDefaultValue.forEach((item,index,newDefaultValue) => {
                    newLocation.push({ name: '请选择', selectName: item.name ,key: item.key})
                })

                this.location = newLocation
                this.selectIndex = newLocation.length - 1

   


                for (let index = 0; index < this.location.length; index++) {
                    
                    let map = {
                        0: 'provinceData',
                        1: 'cityData',
                        2: 'areaData',
                        3: 'townsData'
                    }

                    if (index == 0) {
                        this.getloadProvinces('', 'provinceData')
                    } else {
                        const element = this.location[index-1];
                        
                        this.getloadProvinces(element.key, map[index])
                   }
                    
                }

                return
            }

            this.getloadProvinces('', 'provinceData')
        },

        //加载地址
        getloadProvinces(prames, addressType) {
            let that = this
            let parameterValue = {}

            //渲染数据
            const dogSwitch = (addressType) => ({
                "provinceData": "provinceData", 
                "cityData": "cityData",
                "areaData": "areaData",
                "townsData": "townsData"
            })[addressType] || "provinceData";



            const dataObj = (data) => ({
                "cityData": "province", //市
                "areaData": "city", //区
                "townsData": "area"
            })[data]


            prames && (parameterValue[dataObj(addressType)] = prames)
            

            const apiType = {
                "provinceData": loadProvincesByMode,  //省
                "cityData": loadCitiesByMode,  //市
                "areaData": loadAreasByMode,  //区
                "townsData": loadTownsByMode //街道
            }
            


            parameterValue.mode = this.mode


            return new Promise((resolve, reject) => {

                apiType[addressType](parameterValue).then(res => {
                    if (res.status == 1) {
                        this[`${dogSwitch(addressType)}`] = res.result
                        resolve(res.result)
                    } else {
                        reject(null)
                    }
                }).catch(error => {
                })
                
            }).catch(error => {
            })


            apiType[addressType](parameterValue).then(res => {
                if (res.status == 1) {
                    this[`${dogSwitch(addressType)}`] = res.result
                }
            })


        },
        
        //地址栏切换
        switchTab(item,index) {
            if (!item.selectName) {
                return
            }   
            this.selectIndex = index  
        },

        async switchAddress(value,key,type) {
            let data = null
            // if (key == this.location[this.selectIndex].key) {
            //     return
            // }
            let tabIndex = 0

            type && (data = await this.getloadProvinces(key, type))

            
           if (key !== this.location[this.selectIndex].key) {
                this.location.forEach((item,index) => {
                    if (index > this.selectIndex) {

                        // item.selectName = ''

                        // item.key = ''
                        this.location.splice(index,this.location.length-1)

                    }
                })

            }

            this.location[this.selectIndex].selectName = value;
            this.location[this.selectIndex].key = key;
			let flag = this.location.some(item => !item.key) || (this.location[ this.selectIndex + 1 ] && this.location[ this.selectIndex + 1 ].key) //用于判断是否要生成下一级请选择
            if(data && data.length > 0 &&  type) (this.selectIndex += 1);
			if(data && data.length > 0 && !flag) this.location = [...this.location,{name: '请选择',selectName: '',key: ''}]
            // (data && data.length > 0 ) &&( this.location = [...this.location,{name: '请选择',selectName: '',key: ''}]);
            // (data && data.length > 0 ) && type && (this.selectIndex += 1)
        },

        close() {
            this.$emit('input', false);
        },
        
        //取消
        onCancel() {
            this.close()
        },

        //确认
        onConfirm() {

            let isSelect = false //默认有选择 
            let addressStr = ''
            let keyId = []
            this.location.forEach((item, index) => {
                if (item.selectName == '') {
                    isSelect = true
                } else {
                    addressStr += item.selectName + ' '
                }
                keyId.push(item.key)
            })


            if (isSelect) {
                this.$toast('尚有未选中项')
                return
            }

            this.selectIndex = 0

            this.$emit('confirm', {keyId,addressStr})

            // if (event) this.$emit(event, this.selectValue);
			this.close();




        }
    },
}
</script>
<style lang="stylus" scoped>
.toolbar {
    display: flex;
    -webkit-box-pack: justify;
    justify-content: space-between;
    height: 0.88rem;
    line-height: 0.88rem;
}

.cancel,
.confirm {
    padding: 0 0.32rem;
    color: #1989fa;
    font-size: 0.28rem;
    background-color: transparent;
    border: none;
    cursor: pointer;
}

.title {
    max-width: 50%;
    font-weight: 500;
    font-size: 0.32rem;
    text-align: center;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.tabs-wrap {
    height: 0.88rem;
    border-top: 1px solid #ebedf0;
    border-bottom: 1px solid #ebedf0;
}

.tabs-wrap .tabs__nav {
    box-sizing: initial;
    height: 100%;
    position: relative;
    display: flex;
    background-color: #fff;
    user-select: none;
    overflow-x: auto;
}

::-webkit-scrollbar{
	display:none
}

.tabs-wrap .tabs__nav .tab {
    position: relative;
    flex: 1;
    box-sizing: border-box;
    min-width: 0;
    padding: 0 0.10rem;
    color: #c8c9cc;
    font-size: 0.28rem;
    line-height: 0.88rem;
    text-align: center;
    cursor: pointer;
    flex: none;
    margin: 0 0.16rem;
}

.tabs-wrap .tabs__nav .tab.action {
    color: #333;
}
.tabs-wrap .tabs__nav .tab.on {
    color: var(--themescolor);
    font-weight: bold;
    position: relative;
}
.tabs-wrap .tabs__nav .tab.on::before {
    content: '';
    position: absolute;
    left:   50%;
    transform: translateX(-50%);
    background-color: var(--themescolor);
    width: 0.50rem;
    height: 0.04rem;
    bottom: 0px;    
    border-radius: 5px;
}



.tabs-content {
    height: 6.80rem;
    overflow: scroll;
    width: auto !important;
    flex-shrink: 0;
    box-sizing: border-box;
}

.cascade-selectorlist {
    padding-left: 0.32rem;
}

.cascade-selectorlist .item:first-child {
    margin-top: 0.36rem;
}

.cascade-selectorlist .item {
    padding: 0.20rem 0;
    font-size: 0.32rem;
}

.cascade-selectorlist .item:last-child {
    margin-bottom: 0.36rem;
}

.cascade-selectorlist .item.action {
    color: var(--themescolor);
}

.send-code {
    flex-shrink: 0;
    font-size:12px;
    color: #666;
    padding: 0 5px;
    border-left: 1px solid #f8f8f8;

}
.bottom_btn {
    height: 48px;
    width: 7.10rem;
    max-width: 750px;
    text-align: center;
    color: #ffffff;
    line-height: 48px;
    font-size: 15px;
    margin: 20px auto 0;
}
</style>